
function toJSON(val){
	if ((val==null)||(val=="")||val=="null"){
	return "\"\"";
	}
	val=val.replace(/\\/g, "\\\\");
	val=val.replace(/"/g, "\\\"");
	val=val.replace(/\n/g, "\\n");
	return "\""+val+"\"";
}
function ColaboxDb(){  
    DBNAME= "colaboxdb";
    db=null;      
    if(typeof ColaboxDb.flag == "undefined"){         
        ColaboxDb.prototype.init = function(){          	        
        	    
						db = google.gears.factory.create('beta.database');    	    
            db.open(DBNAME);
            //this.dropDatabase();
            
						rs = db.execute("SELECT count(*) FROM sqlite_master WHERE type='table' and name='colaboxcfg';");				
						if (rs.field(0)==0) {
							  rs.close();							  
							  //init  colaboxcfg
							  
							  db.execute( 'create table if not exists colaboxcfg' +
		             ' (id INTEGER PRIMARY KEY,cfgname text,value text,btime text,desc text)');
		        
		            //init parameters	       
		            //set version
			        	//this.setValFromCfg('version','b0.1','ColaBox版本号');
			          this.setValFromCfg('save_time_interval','10','notepad 每次保存的时间间隔');
			          this.setValFromCfg('AutoCache','true','自动localserver cache 标志');//AutoCache
			          
			          
						}
						rs.close();			
						// init notepad table;
						db.execute(
             'create table if not exists notepad' +
             ' (id INTEGER PRIMARY KEY,title text,content text,btime text,ctime text,syncflag integer,type integer,deleteflag integer,synccounts integer)'
             
             );
						//this.dropDatabase();
								
        };
        ColaboxDb.prototype.setValFromCfg=function(name,val,desc){
		        rs = db.execute("select id from colaboxcfg where cfgname='"+name+"'");					
					  if (rs.isValidRow()) {  
					    id=rs.field(0);
					    rs.close();
					    db.execute("update colaboxcfg set value='"+val+"',btime='' where id='"+id+"'");
					}else{
      			  db.execute('insert into colaboxcfg values (?,?,?,?,?)', [null,name,val,null,desc]);
					}				
				
	     };
       ColaboxDb.prototype.getValFromCfg=function(name){
      		rs = db.execute("select value from colaboxcfg where cfgname='"+name+"'");
					t=null;
					if (rs.isValidRow()) {
					
					  t=rs.field(0);
					}
					rs.close();
					
					if (t==null) t="";
					
					return t;
					
      };
      ColaboxDb.prototype.dump=function(name){
		    
			   rs = db.execute('select * from '+name);			
			   var str="";
			   while (rs.isValidRow()) {
			  		for (i=0;i<rs.fieldCount();i++){
						   str+=rs.field(i)+'@';
			      }			  
			      str='';
			      rs.next();
			   }
			   rs.close();
      };
      ColaboxDb.prototype.getSyncVal=function(){		    
			   rs = db.execute('select id,title,content,btime,ctime,type,deleteflag,synccounts from notepad where syncflag=0 order by btime limit 1');			
			   var str="";
			   while (rs.isValidRow()) {
				    str='{id:'+rs.field(0)+',title:'+toJSON(rs.field(1))+',content:'+toJSON(rs.field(2))+',type:'+toJSON(rs.field(5))+',btime:'+toJSON(rs.field(3))+',ctime:'+toJSON(rs.field(4))+',deleteflag:"'+rs.field(6)+'",synccounts:'+rs.field(7)+'}';
			      rs.next();
			   }			   
			   rs.close();
			   return str;
      };      
      ColaboxDb.prototype.setSyncFlag=function(id){		    
			   db.execute("update notepad set syncflag=1,synccounts=synccounts+1 where id=?",[id]);			
			   	
      }; 
      ColaboxDb.prototype.drop=function(name){
      	 db.execute('drop table '+name);
      };
      ColaboxDb.prototype.dropAlltable=function(){
      	//db.close(DBNAME);
      	//this.drop("colaboxcfg");
      	//this.drop("notepad");
      	db.execute("delete from colaboxcfg");		
      	//db.execute("delete from notepad");		
      	db.execute("update notepad set syncflag=1,deleteflag=1");
      }; 
      ColaboxDb.prototype.close=function(){
      	//db.close(DBNAME);
      	db.close();
      };
      
      /*
      ColaboxDb.prototype.isFirstStart=function(){
      	 if ((this.getValFromCfg("isFirstStart")==null)||(this.getValFromCfg("isFirstStart")==1)){
      	 		return true; 
      	 }else{
      	 	  return false;
      	 }
      };  
      */
        
      this.init();
      ColaboxDb.flag = true;  
    }  
} 

var filesToCapture = [
  '../css/main.css',
  '../css/moodatatable.css',
  '../css/notepad.css',  
  '../themes/default/css/Content.css',
  '../themes/default/css/Core.css',
  '../themes/default/css/Layout.css',
  '../themes/default/css/Window.css',
  '../themes/default/css/Tabs.css',  
  '../scripts/gears_init.js',    
  '../scripts/excanvas_r43.js',
  '../scripts/mootools-1.2.2.2-more.js',
  '../scripts/tools.js',
  '../scripts/mootools-1.2.2-core.js',
  '../scripts/colabox-init.js',
  '../scripts/colabox-worker.js',
  '../scripts/gears_init.js',
  '../scripts/notepad-init.js',
  '../scripts/notepad-worker.js',
  '../scripts/moodatatable.js',  
  '../scripts/optionwindow-init.js',  
  '../scripts/source/Core/Core.js',    
  '../scripts/source/Layout/Layout.js',    
  '../scripts/source/Window/Window.js',    
  '../scripts/source/Window/Modal.js',    
  '../scripts/source/Components/Tabs.js',    
  '../images_app/border-2.gif',
	'../images_app/border.gif',
	'../images_app/b_help.png',
	'../images_app/b_more.png',
	'../images_app/b_save.png',
	'../images_app/b_search.png',
	'../images_app/text_bg.gif',
	'../images_app/text_bg2.gif',
	'../images_app/user_login.png',
	'../images_app/user_login_offline.png',
	'../images_app/vista_toolbar_back.gif',
	'../images_app/vista_toolbar_left.png',
	'../images_app/vista_toolbar_right.png',
	'../images_app/logo_big.png',	
	'../images_app/notepad_edit.png',	
	'../images_app/notepad_save.png',	
	'../images_app/notepad_del.png',		
  '../pages/zh-cn/notepad.html',
  '../pages/zh-cn/panel-tabs.html',
  '../pages/zh-cn/aboutwindow.html',
  '../pages/zh-cn/loginwindow.html',
  '../pages/zh-cn/updatewindow.html',
  '../pages/zh-cn/optionwindow.html',
  '../pages/en-us/notepad.html',
  '../pages/en-us/panel-tabs.html',
  '../pages/en-us/aboutwindow.html',
  '../pages/en-us/loginwindow.html',
  '../pages/en-us/updatewindow.html',
  '../pages/en-us/optionwindow.html',
  '../index.html'  
];


var captureCallback;
var updateMSG;

function ColaboxLocalServer(){  
    STORE_NAME = "colaboxlocalserverStore";
   // localServer=null; 
    store=null;  
    statustxt="";   
    if(typeof ColaboxLocalServer.flag == "undefined"){         
        ColaboxLocalServer.prototype.init = function(){          	        
        	   localServer = google.gears.factory.create('beta.localserver');	
        	 
        	   //localServer.createStore(STORE_NAME);
        	   
        };
        

       
       ColaboxLocalServer.prototype.update=function(msg){   
          	localServer.createStore(STORE_NAME);    	
       	    store = localServer.openStore(STORE_NAME);
       	    updateMSG=msg;
       	    if (!store) {
					    this.addStatus('Please create a store for the captured resources');
					    google.gears.workerPool.sendMessage([{ret:"true",val:statustxt,msgId:msg.body[0].msgId}], msg.sender);
					    return;
					  }	
					  	
       	    store.capture(filesToCapture, this.captureCallback); 
       	    
       	    
      	 
       };  
       ColaboxLocalServer.prototype.captureCallback=function(url, success, captureId) {
         statustxt=(url + ' captured ' + (success ? 'succeeded' : 'failed'));	
         var val2;
				 if (url ==filesToCapture[0]) {
				 //if (url=="../css/main.css"){
				 	  google.gears.workerPool.sendMessage([{ret:"Capture",status:"start",val:statustxt,successFlag:success,progress:val2,msgId:updateMSG.body[0].msgId}], updateMSG.sender);
				 }else if (url =="../index.html") {
				// }else if (url ==filesToCapture[filesToCapture.length-1]) {
				 	  google.gears.workerPool.sendMessage([{ret:"Capture",status:"stop",val:statustxt,successFlag:success,progress:val2,msgId:updateMSG.body[0].msgId}], updateMSG.sender);
				 }else{
				 	  google.gears.workerPool.sendMessage([{ret:"Capture",status:"ing",val:statustxt,successFlag:success,progress:val2,msgId:updateMSG.body[0].msgId}], updateMSG.sender);
				 }
       }
       ColaboxLocalServer.prototype.removeStore=function(msg) {
				  // We call openStore() to test for it's existence prior to removing it
				  if (localServer.openStore(STORE_NAME)) {
				    localServer.removeStore(STORE_NAME);
				    this.addStatus('Removed the store');
				  } else {
				    this.addStatus('The store does not exist');
				  }
				  google.gears.workerPool.sendMessage([{ret:"true",val:statustxt,msgId:msg.body[0].msgId}], msg.sender);
				
			 };
			 ColaboxLocalServer.prototype.addStatus=function(txt){
      	   statustxt=txt;
       };
    
       this.init();
       ColaboxLocalServer.flag = true;  
    }  
} 





var notepadId;			

var colaboxdb=new ColaboxDb;
var colaboxloaclserver=new ColaboxLocalServer;
var   GoogleUserToken1=colaboxdb.getValFromCfg("GoogleUserToken1");  
var   GoogleUserToken2=colaboxdb.getValFromCfg("GoogleUserToken2"); 

//colaboxloaclserver.removeStore(); 
var updateWork=function (a, b, message) {	
				
			//str="msgid="+message.body[0].msgId;
      //MSG=message;
			
			if  (message.body[0].msgId==0){				  
				 //colaboxloaclserver.removeStore();
				 colaboxdb.dropAlltable();
				 google.gears.workerPool.sendMessage([{ret:"true",val:"clear all data success . Please retry Colabox .",msgId:message.body[0].msgId}], message.sender);			  
				 
			}else if (message.body[0].msgId==1){  //删除stroe 和 版本号
				 colaboxloaclserver.removeStore(message);
				 colaboxdb.setValFromCfg("version",-1,"version");
				 //version=-1;
				 google.gears.workerPool.sendMessage([{ret:"true",val:"delete localServer stroe ok",msgId:message.body[0].msgId}], message.sender);
					
			}else if (message.body[0].msgId==3){  //保存用户名和密码 并且测试 
				 colaboxdb.setValFromCfg("GoogleUserName",message.body[1].Username,"");
				 colaboxdb.setValFromCfg("GooglePassword",message.body[1].Password,"");
				 var request = google.gears.factory.create('beta.httprequest');
									      request.open('POST', '../colaboxServ?mod=notepad&t='+new Date().getTime());
												request.onreadystatechange = function() {
											  if (request.readyState == 4) {												   
															   try {
																			    if (request.status==200){		
																			           // google.gears.workerPool.sendMessage([{ret:"true",val:"request.responseText",Gusername:u,Gpassword:p,msgId:message.body[0].msgId}], message.sender);	
																			         eval("val="+request.responseText);                                               
                                               if (val.ret=="true"){
                                               	   colaboxdb.setValFromCfg("GoogleUserToken1",val.token1,"");
                                               	   colaboxdb.setValFromCfg("GoogleUserToken2",val.token2,"");
                                               	   GoogleUserToken1=colaboxdb.getValFromCfg("GoogleUserToken1");  
                                                   GoogleUserToken2=colaboxdb.getValFromCfg("GoogleUserToken2"); 
                                                   google.gears.workerPool.sendMessage([{ret:"true",val:"save test user ok .",msgId:message.body[0].msgId}], message.sender);	                     
                                               }else{
                                               	   colaboxdb.setValFromCfg("GoogleUserToken1","","");
                                               	   colaboxdb.setValFromCfg("GoogleUserToken2","","");
                                               	   GoogleUserToken1="";  
                                                   GoogleUserToken2="";                                                	   
                                               	   google.gears.workerPool.sendMessage([{ret:"true",val:"save test user error ."+val.val,msgId:message.body[0].msgId}], message.sender);	
                                               } 
																			    }else{ 
																			    	
																			    	    google.gears.workerPool.sendMessage([{ret:"true",val:"save test user error .",msgId:message.body[0].msgId}], message.sender);	
																			    }
															     } catch(e) {google.gears.workerPool.sendMessage([{ret:"true",val:"save test user error .",msgId:message.body[0].msgId}], message.sender);	}												    
												  }
												};											

										request.send('[{Type:"testLogin"},{Gusername:"'+message.body[1].Username+'",Gpassword:"'+message.body[1].Password+'"}]');
				 //version=-1;
				 //google.gears.workerPool.sendMessage([{ret:"true",val:"save google account ok",msgId:message.body[0].msgId}], message.sender);		
		  }else if (message.body[0].msgId==4){  //get 			 
				 c=colaboxdb.getValFromCfg("AutoCache");
				 
				 //version=-1;
				 google.gears.workerPool.sendMessage([{ret:"true",val:"get ok",AutoCache:c,msgId:message.body[0].msgId}], message.sender);	
			}else if (message.body[0].msgId==5){  //get			 
				 u=colaboxdb.getValFromCfg("GoogleUserName");
				 p=colaboxdb.getValFromCfg("GooglePassword");

				 
				 //version=-1;
				 google.gears.workerPool.sendMessage([{ret:"true",val:"save google account ok",Gusername:u,Gpassword:p,msgId:message.body[0].msgId}], message.sender);	
			}else if (message.body[0].msgId==6){  // 		 

				 colaboxdb.setValFromCfg("AutoCache",message.body[1].AutoCache);

				 google.gears.workerPool.sendMessage([{ret:"true",val:"save AutoCache flag "+message.body[1].AutoCache+" success .",msgId:message.body[0].msgId}], message.sender);		
			}else if (message.body[0].msgId==2){  
				//version=colaboxdb.getValFromCfg("version");
				var request = google.gears.factory.create('beta.httprequest');
				request.open('POST', '../colaboxServ?mod=notepad&t='+new Date().getTime());
												request.onreadystatechange = function() {
											  if (request.readyState == 4) {												   
															   try {
																			    if (request.status==200){	
																			    	   google.gears.workerPool.sendMessage([{ret:"onlinestatus",val:1,step:1,msgId:message.body[0].msgId}], message.sender);	
																			           // google.gears.workerPool.sendMessage([{ret:"true",val:"request.responseText",Gusername:u,Gpassword:p,msgId:message.body[0].msgId}], message.sender);	
																			         eval("val="+request.responseText);                                               
                                               if (val.ret=="true"){
                                               	  colaboxdb.setSyncFlag(val.val);
                                                  google.gears.workerPool.sendMessage([{ret:"true",val:"auto sync to docs .",msgId:message.body[0].msgId}], message.sender);	                     
                                               }else{                                           
                                               	  google.gears.workerPool.sendMessage([{ret:"false",val:"auto sync to docs err."+val.val,msgId:message.body[0].msgId}], message.sender);
                                               } 
																			    }else{ 
																			    	    google.gears.workerPool.sendMessage([{ret:"onlinestatus",val:0,step:2,msgId:message.body[0].msgId}], message.sender);
																			    }
															     } catch(e) {google.gears.workerPool.sendMessage([{ret:"onlinestatus",val:0,step:3,msgId:message.body[0].msgId}], message.sender);	}												    
												  }
												};											

          if (GoogleUserToken1==""){       
						google.gears.workerPool.sendMessage([{ret:"onlinestatus",val:0,step:4,msgId:message.body[0].msgId}], message.sender);
				  }else {
				  	//google.gears.workerPool.sendMessage([{ret:"onlinestatus",val:1}], message.sender);
				  	
				  	str=colaboxdb.getSyncVal();
				  	if (str!=""){
				  			request.send('[{Type:"autoSync"},{Token1:"'+GoogleUserToken1+'",Token2:"'+GoogleUserToken2+'"},'+str+']');
				    }
				  	//request.send('[{Type:"testLogin"},{Gusername:"1",Gpassword:"2"}]');
				  }
				
			}else if (message.body[0].msgId==7){  
				version=colaboxdb.getValFromCfg("version");
				var request = google.gears.factory.create('beta.httprequest');
				request.open('GET', 'version.json?t='+new Date().getTime());
							request.onreadystatechange = function() {
							  if (request.readyState == 4) {
							    //console.write(request.responseText);
							        ret=0;
										  try {
														    if (request.status==200){														       													       
														       if (colaboxdb.getValFromCfg("AutoCache")=="true"){														       	
														             eval("ret="+request.responseText);
														             
																			   if (ret.version!=version){																   	
																			    	  colaboxloaclserver.update(message);
																			    	  colaboxdb.setValFromCfg("version",ret.version,"version ");
																			    	  version=ret.version;
																			    }else{
																			    	 google.gears.workerPool.sendMessage([{ret:"Capture",status:"stop",val:"nowindow",msgId:message.body[0].msgId}], message.sender);
																			    }		
																			    							    																    
																			    //google.gears.workerPool.sendMessage([{ret:"true",val:"design by Untosil@gmail.com @2008-2009",msgId:message.body[0].msgId}], message.sender);
														       }else{
														       	  google.gears.workerPool.sendMessage([{ret:"Capture",status:"stop",val:"nowindow",msgId:message.body[0].msgId}], message.sender);
														       }
                                 }
														    	 
										   } catch(e) {
										   	    ret=0;
														google.gears.workerPool.sendMessage([{ret:"Capture",status:"stop",val:"nowindow",msgId:message.body[0].msgId}], message.sender);
										   }
							 }
							};
					request.send();
			}
			

			
}
google.gears.workerPool.onmessage =updateWork;

